<?php

namespace app\index\controller;


use app\common\model\Category;

class Lists extends Common
{
    //载入模板
    public function index(){
        //2.处理title标签
        $conf = ['title'=>'Mr.Xiong教学博客-列表页'];
        $this->assign('conf',$conf);

        $cid = input('param.cid');
        $tid = input('param.tid');
        //点击分类进来
        if($cid){
            //通过cid获取自己的子类,因为子类的文章也属于父类
            $cids = (new Category())->getSon(db('category')->select(),$cid);
            //将自己追加进来
            $cids[] = $cid;
            //处理标题内容
            $headData = [
                'type'=>'分类',
                'name'=>db('category')->where('cid',$cid)->value('cname'),
                'total'=>db('article')->whereIn('category_cid',$cids)->count()
            ];
            //处理该分类对应的文章  文章表和分类表关联
            $articleData = db('article')
                         ->alias('a')
                         ->join('__CATEGORY__ c','a.category_cid = c.cid')
                         ->whereIn('a.category_cid',$cids)
                         ->where('is_recycle',0)
                         ->order('sendtime desc')
                         ->paginate(2);
            $page = $articleData->render();
        }
        //点击标签进来
        if($tid){
            //处理标题内容
            $headData = [
                'type'=>'标签',
                'name'=>db('tag')->where('tid',$tid)->value('tname'),
                'total'=>db('article_tag')->where('tag_tid',$tid)->count()
            ];
            //处理该标签对应的文章   文章表与文章标签中间表,分类表关联
            $articleData = db('article')
                         ->alias('a')
                         ->join('__ARTICLE_TAG__ at','a.aid = at.article_aid')
                         ->join('__CATEGORY__ c','a.category_cid = c.cid')
                         ->where('at.tag_tid',$tid)
                         ->where('is_recycle',0)
                         ->order('sendtime desc')
                         ->paginate(10);
            $page = $articleData->render();
        }
        //不管分类进来还是标签进来都要获取文章对应的标签  所以我共同处理了这个数据
        //处理好文章表和分类表关联的数据  并找见对应的标签数据
        $articleData = $articleData->toArray();
        $articleData = $articleData['data'];
        foreach($articleData as $k=>$v){
            $articleData[$k]['tags'] = db('article_tag')
                                      ->alias('at')
                                      ->join('__TAG__ t','at.tag_tid = t.tid')
                                      ->where('at.article_aid',$v['aid'])
                                      ->field(['tid','tname'])
                                      ->select();
        }
        //分配变量
        $this->assign('headData',$headData);
        $this->assign('page',$page);
        $this->assign('articleData',$articleData);
        //1.载入模版
        return view();
    }
}
